/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package administrador;

import java.math.RoundingMode;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;


/**
 *
 * @author DanielSilva
 */
public class Vent_Mayoriza extends javax.swing.JPanel {

    Usuario user;
    int bodega;
    Conexion conexion;
    AdministradorDiario diarioEnt;
    AdministradorView aview;
    //Guardo los paneles en:
    List vectMayor = new ArrayList();
    NumberFormat nf = NumberFormat.getNumberInstance();

    /**
     * Creates new form Vent_Mayoriza
     */
    public Vent_Mayoriza(Conexion cEnt, int BEnt, Usuario user, AdministradorDiario diarioEnt, AdministradorView aview) {
        DecimalFormat dec = (DecimalFormat) nf;
        dec.applyPattern("###.##");
        //Configuro Redondeo
        nf.setMaximumFractionDigits(2);
        nf.setRoundingMode(RoundingMode.HALF_UP);

        this.aview = aview;
        this.diarioEnt = diarioEnt;
        bodega = BEnt;
        this.user = user;
        conexion = cEnt;
        initComponents();
        refrescar();
        muestraMayor();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    public void refrescar() {
        scrol.removeAll();
        String codigoDiario = diarioEnt.cb_codigo.getItemAt(diarioEnt.cb_codigo.getSelectedIndex()).toString();
        txt_codDiario.setText(codigoDiario);
        String DATE_FORMAT = "yyyy-MM-dd";//Refer Java DOCS for formats
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
        txt_fecha.setText(sdf.format(diarioEnt.txt_fecha.getTime()));


    }
    
    
    public List sacoCuentas(){
//Saco las Cuentas de la Empresa y las Guardo en un Vector:
    List cuentas=new ArrayList();
        ResultSet resp = conexion.consultarBase("SELECT * FROM tercernivel;");
        int n1 = 0;
        int n2 = 0;
        int n3 = 0;
        String codigoCuenta = "";
        String nombreCuenta="";
        
        try {
            while (resp.next()) {
                List datos=new ArrayList();
                n1 = resp.getInt(1);
                n2 = resp.getInt(2);
                n3 = resp.getInt(3);
                codigoCuenta = n3 + "," + n2 + "," + n1;
                nombreCuenta=resp.getString(4);
                datos.add(codigoCuenta);
                datos.add(nombreCuenta);
                //System.out.println("Las cuentas son:"+codigoCuenta+" valor:"+nombreCuenta);
                cuentas.add(datos);
            }
        }catch(SQLException e){
        }
return cuentas;
}

public List sacoAsientosDetalles(){
List detalles=new ArrayList();
//Valido por periodo o por mes:
String hoyFecha=new java.sql.Date(System.currentTimeMillis()).toString();    
int seleccion=cb_opcion.getSelectedIndex();
String xfecha="";
if(seleccion==0){//Sacar resultados x mes:
   xfecha="and year(fecha_dia)=year('"+hoyFecha+"') and month(fecha_dia)=month('"+hoyFecha+"')";
   }else{}//Sacar resultados x periodo

//Saco Asientos:
String codDiario = txt_codDiario.getText();
    ResultSet resp2 = conexion.consultarBase("SELECT cod_tercernivel,cod_segundonivel,cod_primernivel,debe,haber FROM asiento a,dtl_asiento d where a.cod_diario="+codDiario+" and d.cod_asiento=a.cod_asiento and (parcial+debe+haber)>0 "+xfecha+" ;");
    try {
        resp2.beforeFirst();
        while (resp2.next()) {
            List datos=new ArrayList();
            int n3 = resp2.getInt(1);
            int n2 = resp2.getInt(2);
            int n1 = resp2.getInt(3);
            String codigoCuenta = n1 + "," + n2 + "," + n3;
            double debe=resp2.getDouble(4);
            double haber=resp2.getDouble(5);
            double valor=debe-haber;
            
            valor=Double.parseDouble(nf.format(valor).replaceAll(",","."));
            datos.add(codigoCuenta);
            datos.add(valor);
            //System.out.println("Los detalles son:"+codigoCuenta+" valor:"+valor);
            detalles.add(datos);
        }
    }catch(SQLException e){}

return detalles;
}

public List pogoDetalleCuentas(List cuentas,List detalles){
//System.out.println("El numero de cuentas son:"+cuentas.size());   
//System.out.println("El numero de detalles son:"+detalles.size());
//Recorro Asientos:
    for(int i=0;i<detalles.size();i++){
     String codigo=(((List)detalles.get(i)).get(0)).toString();
     double valor=Double.parseDouble(((List)detalles.get(i)).get(1).toString());
     ponerCuenta(cuentas,codigo,valor);
    //System.out.println("El detalle es:"+codigo+" valor:"+valor);
    }


return cuentas;
}

public void ponerCuenta(List cuentas,String codigo,double valor){
    int tamano=cuentas.size();
    int cont=0;
    while(cont<tamano){
        List datos=((List)cuentas.get(cont));
        String codCuenta=datos.get(0).toString();
        //Compara:
        if(codCuenta.equals(codigo)){
        //System.out.println("Encontro!!"+codCuenta); 
        ((List)cuentas.get(cont)).add(valor);
        break;
        }
    cont++;
    }
}

public void sacoMayor(){
//Creo el Vector donde se guardan los datos Cuentas
List cuentas=sacoCuentas();
List detalles=sacoAsientosDetalles();
List mayor=pogoDetalleCuentas(cuentas,detalles);
//muestroMayor(mayor);
creoMayor(mayor);
}

public void creoMayor(List mayor){
    //Limpio el Vector de Saldos:
    vectMayor.clear();
    
    //Creo Mayor:
    for(int i=0;i<mayor.size();i++){
    //Creo el panel:
    panelCuenta pc=new panelCuenta();
    List datos=new ArrayList();
    //Saco la cuenta:
    List cuenta=(List) mayor.get(i);
    String codigo=cuenta.get(0).toString();
    String nombre=cuenta.get(1).toString();
    
    pc.ponerNombre(nombre);
    pc.ponerCodigo(codigo);
    //Agrego al vector de saldos:
    datos.add(nombre);
    datos.add(codigo);
    
    for(int j=2;j<cuenta.size();j++){
        //Creo el panel para para Guardar los Datos:
        double detalle=Double.parseDouble(cuenta.get(j).toString());
        if(detalle>0){
        pc.ponerDebe(detalle);
        }else{
        pc.ponerHaber(detalle);
        }
        
    }
    pc.actualizaTotales();
    datos.add(pc.sacaSaldo());
    vectMayor.add(datos);
    scrol.add(nombre,pc);
    
    }
    
    
}

public void muestroMayor(List mayor){
int tamano=mayor.size();
    int cont=0;
    while(cont<tamano){
        List cuenta=(List)mayor.get(cont);
        String codigo=cuenta.get(0).toString();
        String nombre=cuenta.get(1).toString();
       //System.out.println("La cuenta es:"+codigo+" "+nombre);
        
        int t=cuenta.size();
        int c=2;
        while(c<t){
            double valor=Double.parseDouble(cuenta.get(c).toString());
           //System.out.println("\t"+valor);
            c++;
        }
        cont++;
        
    }
   
}



 public void muestraMayor() {
sacoMayor();     
 }   

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txt_codDiario = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txt_fecha = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cb_opcion = new javax.swing.JComboBox();
        bt_refrescar = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        btEstadoResult = new javax.swing.JButton();
        estadoFinanciero = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        scrol = new javax.swing.JTabbedPane();

        setLayout(new java.awt.BorderLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Diario");

        jLabel2.setText("Fecha Diario:");

        jLabel3.setText("Opciones:");

        cb_opcion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "mes", "anio" }));

        bt_refrescar.setText("Refrescar");
        bt_refrescar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_refrescarActionPerformed(evt);
            }
        });

        jLabel4.setText("Informes Financieros");

        jButton2.setText("Balance de Comprobacion");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        btEstadoResult.setText("Estado de Resultados");
        btEstadoResult.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEstadoResultActionPerformed(evt);
            }
        });

        estadoFinanciero.setText("Estado Financiero");
        estadoFinanciero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                estadoFinancieroActionPerformed(evt);
            }
        });

        scrol.setTabPlacement(javax.swing.JTabbedPane.LEFT);
        jScrollPane1.setViewportView(scrol);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 631, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(txt_fecha, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cb_opcion, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(txt_codDiario, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(bt_refrescar, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(45, 45, 45)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(estadoFinanciero, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btEstadoResult, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)))))
                .addContainerGap(79, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addGap(4, 4, 4)
                        .addComponent(btEstadoResult))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(txt_codDiario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(bt_refrescar))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(txt_fecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cb_opcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(estadoFinanciero)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        add(jPanel1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void bt_refrescarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_refrescarActionPerformed
        // TODO add your handling code here:
        
        refrescar();
        muestraMayor();
    }//GEN-LAST:event_bt_refrescarActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        VentBalanceComprobacion vbc=new VentBalanceComprobacion(conexion,user,aview,vectMayor);
    String tabnombre="Contabilidad BalanceComprobacion";
    aview.tp_controles.addTab(tabnombre,vbc);
    aview.ventanas.add(vbc);
    aview.seleccionarTab();  
    }//GEN-LAST:event_jButton2ActionPerformed

    private void btEstadoResultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEstadoResultActionPerformed
        // TODO add your handling code here:
         EstadoResultados ers=new EstadoResultados(conexion,user,aview,vectMayor);
    
    String tabnombre="Contabilidad Estado de Resultados";
    aview.tp_controles.addTab(tabnombre,ers);
    aview.ventanas.add(ers);
    aview.seleccionarTab();  
        
    }//GEN-LAST:event_btEstadoResultActionPerformed

    private void estadoFinancieroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_estadoFinancieroActionPerformed
        // TODO add your handling code here:
         balanceGeneral ef=new balanceGeneral(conexion,vectMayor);
    String tabnombre="Contabilidad Balance General";
    aview.ventanas.add(ef);
    aview.tp_controles.addTab(tabnombre,ef);
    aview.seleccionarTab();
        
    }//GEN-LAST:event_estadoFinancieroActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btEstadoResult;
    private javax.swing.JButton bt_refrescar;
    private javax.swing.JComboBox cb_opcion;
    private javax.swing.JButton estadoFinanciero;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane scrol;
    private javax.swing.JTextField txt_codDiario;
    private javax.swing.JTextField txt_fecha;
    // End of variables declaration//GEN-END:variables
}
